home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 150 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.5 KB  |  63 lines

  1. Path: unix.sri.com!usenet
  2. From: mklenk@updike.sri.com (Mark Klenk)
  3. Newsgroups: comp.std.c
  4. Subject: Re: memcpy
  5. Date: 19 Jan 1996 16:10:31 GMT
  6. Organization: SRI International
  7. Message-ID: <4dofpn$fk9@unix.sri.com>
  8. References: <4dn0gu$itc@mirv.unsw.edu.au>
  9. Reply-To: mklenk@updike.sri.com
  10. NNTP-Posting-Host: 204.75.161.40
  11.  
  12. Geoff Wong wrote:
  13. >
  14. >Can memcpy cope with very complex objects?
  15.  
  16.     I think what you're asking is whether memcpy() will perform
  17.     what is called a "deep" copy.  No, it will not.  memcpy()
  18.     simply copies a block of memory (contiguous bytes) from one
  19.     location to another.  If you use it to copy an object that
  20.     contains pointers, the copy of it will contain those same
  21.     pointers, not new pointers to copies of what the original
  22.     ones pointed to.  This is called a "shallow" copy, and is
  23.     all that memcpy()/memmove() can do.
  24.  
  25.     If you want to implement a deep copy, you'll have to write
  26.     the routine yourself, something like:
  27.  
  28. typedef struct {
  29.     int a, b;
  30.     char * bar;
  31. } Foo;
  32.  
  33. Foo * FooClone(Foo const * original)
  34. {
  35.     Foo * foo;
  36.  
  37.     foo = (Foo *)malloc(sizeof(Foo));
  38.     if (NULL != foo) {
  39.         size_t size = strlen(original->bar) + 1;
  40.         foo->a = original->a;
  41.         foo->b = original->b;
  42.         foo->bar = (char *)malloc(size);
  43.         if (NULL == foo->bar) {
  44.             free(foo);
  45.             foo = NULL;
  46.         } else {
  47.             memcpy(foo->bar, original->bar, size);
  48.         }
  49.     }
  50.  
  51.     return foo;
  52. }
  53.  
  54.     To sidetrack a little, this is what the copy constructor in
  55.     C++ is often used for.
  56.  
  57. ---
  58.  
  59. mklenk@coronacorp.com       (Mark Klenk)
  60.  
  61.  
  62.  
  63.